﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Ribbon.Gallery;
using DevExpress.XtraEditors.ColorWheel;
using DevExpress.XtraNavBar;
using DevExpress.XtraNavBar.ViewInfo;
using DevExpress.XtraPrinting;
using DevExpress.XtraRichEdit;
using NAGFwk.UI.Modules;
using NAGFwk.UI.Properties;

namespace NAGFwk.UI
{
    public partial class FrmMain : RibbonForm
    {
        readonly ModulesNavigator _modulesNavigator;
        readonly ZoomManager _zoomManager;
        readonly List<BarItem> _allowCustomizationMenuList = new List<BarItem>();
        internal ZoomManager ZoomManager { get { return _zoomManager; } }
        internal BackstageViewButtonItem SaveAsMenuItem { get { return bvbiSaveAs; } }
        internal BackstageViewButtonItem SaveAttachmentMenuItem { get { return bvbiSaveAttachment; } }
        internal InRibbonGallery TaskGallery { get { return rgbiCurrentViewTasks.Gallery; } }
        public RibbonStatusBar RibbonStatusBar { get { return ribbonStatusBar1; } }
        public IPrintable CurrentPrintableComponent
        {
            get
            {
                if (_modulesNavigator.CurrentModule != null)
                    return _modulesNavigator.CurrentModule.PrintableComponent;
                else
                    return null;
            }
        }
        public IPrintable CurrentExportComponent
        {
            get
            {
                if (_modulesNavigator.CurrentModule != null)
                    return _modulesNavigator.CurrentModule.ExportComponent;
                else
                    return null;
            }
        }
        public RichEditControl CurrentRichEdit
        {
            get
            {
                if (_modulesNavigator.CurrentModule != null)
                    return _modulesNavigator.CurrentModule.CurrentRichEdit;
                else
                    return null;
            }
        }
        public string CurrentModuleName
        {
            get
            {
                if (_modulesNavigator.CurrentModule != null)
                    return _modulesNavigator.CurrentModule.ModuleName;
                else
                    return string.Empty;
            }
        }

        public FrmMain()
        {
            InitializeComponent();
            SkinHelper.InitSkinGallery(rgbiSkins);
            RibbonButtonsInitialize();
            _modulesNavigator = new ModulesNavigator(ribbonControl1, pcMain);
            _zoomManager = new ZoomManager(ribbonControl1, _modulesNavigator, beiZoom);
            SetPageLayoutStyle();
            WindowState = FormWindowState.Maximized;
            
        }
        public void NavigationInitialize(string defaultModuleButtonName = null)
        {
            var currentAvailableGroups = nbcMainMenu.Groups.ToList();
            foreach (var @group in currentAvailableGroups)
                foreach (NavBarItemLink link in @group.ItemLinks)
                {
                    BarButtonItem item = new BarButtonItem(ribbonControl1.Manager, link.Item.Caption) { Name = link.Item.Name, Tag = link, Glyph = link.Item.SmallImage };
                    item.ItemClick += item_ItemClick;
                    bsiNavigation.ItemLinks.Add(item);
                }
            if (!string.IsNullOrEmpty(defaultModuleButtonName))
            {
                NavBarItemLink defaultModule = null;
                foreach (var @group in currentAvailableGroups)
                 {
                     defaultModule = @group.ItemLinks.SingleOrDefault(y => y.Item.Name == defaultModuleButtonName);
                     if(defaultModule!=null)break;
                 }

                 _modulesNavigator.ChangeSelectedItem(defaultModule, null);
            }
        }

        void item_ItemClick(object sender, ItemClickEventArgs e)
        {
            foreach (var @group in nbcMainMenu.Groups.ToList())
                if (@group.ItemLinks.SingleOrDefault(x => x.Item.Name == e.Item.Name) != null)
                {
                    @group.SelectedLink = (NavBarItemLink)e.Item.Tag;
                    break;
                }
        }
        void RibbonButtonsInitialize()
        {
            //foreach (RibbonPage page in ribbonControl1.Pages)
            //{
            //    //page.Text = _rm.GetString(page.Name);
            //    foreach (RibbonPageGroup @group in page.Groups)
            //    {
            //        //@group.Text = _rm.GetString(@group.Name);
            //        foreach (var item in @group.ItemLinks)
            //        {
            //            if (item.GetType() == typeof(BarSubItem))
            //                ((BarSubItem)item).Caption = _rm.GetString(((BarSubItem)item).Name);
            //            else if (item.GetType() == typeof(BarButtonItem))
            //                ((BarButtonItem)item).Caption = _rm.GetString(((BarButtonItem)item).Name);
            //            else if (item.GetType() == typeof(BarButtonItemLink))
            //                ((BarButtonItemLink)item).Caption = _rm.GetString(((BarButtonItemLink)item).Item.Name);
            //        }
            //    }
            //}


            //bvbiSaveAs.Caption = _rm.GetString(bvbiSaveAs.Name);
            bvbiSaveAs.Tag = bvbiSaveAs.Caption;
            //bvbiSaveAttachment.Caption = _rm.GetString(bvbiSaveAttachment.Name);
            bvbiSaveAttachment.Tag = bvbiSaveAttachment.Caption;
            //bvbiExit.Caption = _rm.GetString(bvbiExit.Name);
            //bvtiExport.Caption = _rm.GetString(bvtiExport.Name);
            //bvtiPrint.Caption = _rm.GetString(bvtiPrint.Name);

            _allowCustomizationMenuList.Add(bsiNavigation);
            _allowCustomizationMenuList.Add(rgbiSkins);
            ribbonControl1.Toolbar.ItemLinks.Add(rgbiSkins);
        }

        void InitGalleryItem(GalleryItem galleryItem, string tag, string description)
        {
            galleryItem.Tag = tag;
            galleryItem.Hint = description;
        }

        void InitBarButtonItem(BarButtonItem buttonItem, object tag)
        {
            InitBarButtonItem(buttonItem, tag, string.Empty);
        }

        void InitBarButtonItem(BarButtonItem buttonItem, object tag, string description)
        {
            buttonItem.ItemClick += bbi_ItemClick;
            buttonItem.Hint = description;
            //buttonItem.Caption = _rm.GetString(buttonItem.Name);
            buttonItem.Tag = tag;
        }

        public void InitNavBarItemLinks(Dictionary<string, Type> childForms)
        {
            nbiSpreadsheet.Tag = new NavBarGroupTagObject("Spreadsheet", typeof(SpreadsheetModule));
            nbiWord.Tag = new NavBarGroupTagObject("Word", typeof(WordModule));

            foreach (var item in childForms)
                foreach (var @group in nbcMainMenu.Groups.ToList())
                {
                    @group.SelectedLinkIndex = -1;
                    if (@group.ItemLinks.FirstOrDefault(x => x.Item.Name == item.Key) != null)
                    {
                        var currentMenu = @group.ItemLinks.FirstOrDefault(x => x.Item.Name == item.Key);

                        if (currentMenu != null)
                            currentMenu.Item.Tag = new NavBarGroupTagObject(item.Key, item.Value);
                    }
                }
        }

        internal void EnableLayoutButtons(bool enabled)
        {
            bbiFlipLayout.Enabled = enabled;
        }

        internal void EnableZoomControl(bool enabled)
        {
            beiZoom.Visibility = enabled ? BarItemVisibility.Always : BarItemVisibility.Never;
        }

        internal void ShowInfo(int? count)
        {
            if (count == null) bsiInfo.Caption = string.Empty;
            else
                bsiInfo.Caption = string.Format(Resources.InfoText, count.Value);
            //HtmlText = _rm.GetString("ShowInfoText");
        }

        string GetModuleName()
        {
            if (string.IsNullOrEmpty(_modulesNavigator.CurrentModule.PartName)) return CurrentModuleName;
            return string.Format("<b>{0}</b>", CurrentModuleName);
        }

        string GetModulePartName()
        {
            if (_modulesNavigator.CurrentModule != null)
                if (string.IsNullOrEmpty(_modulesNavigator.CurrentModule.PartName)) return null;
            return string.Format(" - {0}", _modulesNavigator.CurrentModule.PartName);
        }

        private void navBarControl1_SelectedLinkChanged(object sender, NavBarSelectedLinkChangedEventArgs e)
        {
            if (e.Link != null)
                _modulesNavigator.ChangeSelectedItem(e.Link, null);
        }

        private void bbi_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_modulesNavigator.CurrentModule != null)
                _modulesNavigator.CurrentModule.ButtonClick(string.Format("{0}", e.Item.Tag));
        }

        private void frmMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (_modulesNavigator.CurrentModule != null)
                _modulesNavigator.CurrentModule.SendKeyDown(e);
        }

        private void navBarControl1_NavPaneStateChanged(object sender, EventArgs e)
        {
            SetPageLayoutStyle();
        }

        private void bvbiExit_ItemClick(object sender, BackstageViewItemEventArgs e)
        {
            Close();
        }

        private void galleryControlGallery1_ItemClick(object sender, GalleryItemClickEventArgs e)
        {
            _modulesNavigator.CurrentModule.ButtonClick(string.Format("{0}", e.Item.Tag));
        }

        private void backstageViewControl1_ItemClick(object sender, BackstageViewItemEventArgs e)
        {
            if (_modulesNavigator.CurrentModule == null) return;
            _modulesNavigator.CurrentModule.ButtonClick(string.Format("{0}", e.Item.Tag));
        }

        void SetPageLayoutStyle()
        {
            bbiNormal.Down = nbcMainMenu.OptionsNavPane.NavPaneState == NavPaneState.Expanded;
            bbiReading.Down = nbcMainMenu.OptionsNavPane.NavPaneState == NavPaneState.Collapsed;
        }

        private void bbiNormal_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (bbiNormal.Down) nbcMainMenu.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
            else
                bbiNormal.Down = true;
        }

        private void bbiReading_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (bbiReading.Down) nbcMainMenu.OptionsNavPane.NavPaneState = NavPaneState.Collapsed;
            else
                bbiReading.Down = true;
        }

        private void rgbiCurrentView_GalleryInitDropDownGallery(object sender, InplaceGalleryEventArgs e)
        {
            e.PopupGallery.GalleryDropDown.ItemLinks.Add(bbiManageView);
            e.PopupGallery.GalleryDropDown.ItemLinks.Add(bbiSaveCurrentView);
            e.PopupGallery.SynchWithInRibbonGallery = true;
        }

        private void rgbiCurrentViewTasks_GalleryItemClick(object sender, GalleryItemClickEventArgs e)
        {
            _modulesNavigator.CurrentModule.ButtonClick(string.Format("{0}", e.Item.Tag));
        }

        private void bvtiPrint_SelectedChanged(object sender, BackstageViewItemEventArgs e)
        {
            if (backstageViewControl1.SelectedTab == bvtiPrint)
                printControl1.InitPrintingSystem();
        }

        private void ribbonControl1_BeforeApplicationButtonContentControlShow(object sender, EventArgs e)
        {
            if (backstageViewControl1.SelectedTab == bvtiPrint) backstageViewControl1.SelectedTab = bvtiInfo;
            bvtiPrint.Enabled = CurrentRichEdit != null || CurrentPrintableComponent != null;
            bvtiExport.Enabled = CurrentExportComponent != null;
        }

        private void ribbonControl1_ShowCustomizationMenu(object sender, RibbonCustomizationMenuEventArgs e)
        {
            e.CustomizationMenu.InitializeMenu();
            if (e.Link == null || !_allowCustomizationMenuList.Contains(e.Link.Item))
                e.CustomizationMenu.RemoveLink(e.CustomizationMenu.ItemLinks[0]);
        }

        internal void ShowReminder(List<Task> reminders)
        {
            bool allowReminders = reminders != null && reminders.Count > 0;
            bbiReminder.Visibility = allowReminders ? BarItemVisibility.Always : BarItemVisibility.Never;
            bsiTemp.Visibility = allowReminders ? BarItemVisibility.Never : BarItemVisibility.Always;
            if (allowReminders)
            {
                bbiReminder.Caption = string.Format(Resources.ReminderText, reminders.Count);
                bbiReminder.Tag = reminders;
            }
        }
        public void ShowInfo(bool visible)
        {
            bsiInfo.Visibility = bsiTemp.Visibility = visible ? BarItemVisibility.Always : BarItemVisibility.Never;
        }

        private void biPrintPreview_ItemClick(object sender, ItemClickEventArgs e)
        {
            ShowPrintPreview();
        }
        protected void ShowPrintPreview()
        {
            if (CurrentPrintableComponent == null) return;
            PrintableComponentLink link = new PrintableComponentLink(new PrintingSystem());
            if (_modulesNavigator.CurrentModule.AllowRtfTitle)
            {
                link.RtfReportHeader = @"{\rtf1\ansi\ansicpg1251\deff0\deflang1049{\fonttbl{\f0\fnil\fcharset0 Segoe UI;}}
{\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\sa200\sl276\slmult1\qc\lang9\f0\fs32 " + CurrentModuleName + @"\par
}";
            }
            link.Component = CurrentPrintableComponent;
            link.CreateDocument();
            link.ShowRibbonPreviewDialog(LookAndFeel);
        }

        internal void OnModuleShown(BaseModule baseModule)
        {
            rpgPrint.Visible = CurrentPrintableComponent != null;
            if (!string.IsNullOrEmpty(CurrentModuleName))
                this.Text = string.Format("Silkey ERP - Actualmente en {0}", CurrentModuleName);
        }

        private void bbiReminder_ItemClick(object sender, ItemClickEventArgs e)
        {
            //TODO:Call Reminders Form
            //using(frmReminders frm = new frmReminders()) {
            //    frm.InitData(bbiReminder.Tag as List<Task>);
            //    if(frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) {
            //        modulesNavigator.CurrentModule.FocusObject(frm.CurrentTask);
            //        modulesNavigator.CurrentModule.ButtonClick(TagResources.TaskEdit);
            //    }
            //}

        }

        private void bbiColorMixer_ItemClick(object sender, ItemClickEventArgs e)
        {
            ColorWheelForm form = new ColorWheelForm
            {
                StartPosition = FormStartPosition.CenterParent,
                SkinMaskColor = UserLookAndFeel.Default.SkinMaskColor,
                SkinMaskColor2 = UserLookAndFeel.Default.SkinMaskColor2
            };
            form.ShowDialog(this);
        }
    }
}
